﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ComLib;
using ComLib.Entities;
using ComLib.Data;
using ComLib.ValidationSupport;


namespace ComLib.Web.Modules.Rolls
{
    public partial class Roll : ActiveRecordBaseEntity<Roll>, IEntity
    {
        /// <summary>
        /// Gets the validator for this entity.
        /// </summary>
        /// <returns></returns>
        protected override IValidator GetValidatorInternal()
        {
            var val = new EntityValidator((validationEvent) =>
            {
                int initialErrorCount = validationEvent.Results.Count;
                IValidationResults results = validationEvent.Results;
                Roll entity = (Roll)validationEvent.Target;
                Validation.IsStringLengthMatch(entity.BloggerName, true, false, true, -1, 150, results, "BloggerName");
                Validation.IsStringRegExMatch(entity.Url, false, RegexPatterns.Url, results, "Url");
                Validation.IsNumericWithinRange(entity.MaxTitleLength, false, false, -1, -1, results, "MaxTitleLength");
                Validation.IsStringIn(entity.FeedFormat, false, false, new string[] { "rss", "atom" }, results, "FeedFormat");
                Validation.IsNumericWithinRange(entity.SortIndex, false, false, -1, -1, results, "SortIndex");
                Validation.IsNumericWithinRange(entity.MaxEntries, false, false, -1, -1, results, "MaxEntries");

                return initialErrorCount == validationEvent.Results.Count;
            });
            return val;
        }


        /// <summary>
        /// Called when [before create].
        /// </summary>
        /// <param name="ctx"></param>
        /// <returns></returns>
        public override bool OnBeforeCreate(object ctx)
        {
            if (MaxTitleLength == 0)
                MaxTitleLength = 15;

            return true;
        }


        /// <summary>
        /// Get active rolls ordered by sortindex and ones that are active.
        /// </summary>
        /// <returns></returns>
        public static IList<Roll> GetActive()
        {
            var result = Find(Query<Roll>.New().Where( r => r.IsActive).Is(true).OrderBy( r => r.SortIndex));
            return result;
        }
    }
}
